// express实现文件上传

const express = require('express')
const app = express();

// 上传成功后返回URL地址
const resourceUrl = `http://127.0.0.1:${port}/`;

// 存储文件目录
const uploadDIr = path.join(__dirname, "/upload");

// destination 设置资源保存路径，filename 设置资源名称
const storage = multer.diskStorage({
  destination: async function (_req, _file, cb) {
    cb(null, uploadDIr);
  },
  filename: function (_req, file, cb) {
    // 设置文件名
    cb(null, `${file.originalname}`);
  },
});

const multerUpload = multer({ storage });

//设置静态访问目录
app.use(express.static(uploadDIr));

app.post("/upload", multerUpload.any(), function (req, res, _next) {
  // req.file 是 `avatar` 文件的信息
  let urls = [];
  //获取所有已上传的文件
  const files = req.files;

  if (files && files.length > 0) {
    //遍历生成url 集合返回给客户端
    urls = files.map((item, _key) => {
      return resourceUrl + item.originalname;
    });
  }

  return res.json({
    REV: true,
    DATA: {
      url: urls,
    },
    MSG: "成功",
  });
});
